﻿using LIU.Framework.Common.Extend;
using LIU.Framework.Core;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace LIU.Framework.WebApi.Filters
{
    /// <summary>
    /// 全局异常处理
    /// </summary>
    public class GlobalExceptionFilter : IExceptionFilter
    {
        //public bool AllowMultiple => true;

        //public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        //{
        //    var ex = actionExecutedContext.Exception.InnerException ?? actionExecutedContext.Exception;
        //    return Task.Run(() =>
        //    {
        //        string controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;
        //        string actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
        //        string param = actionExecutedContext.Request.Method.ToString();
        //        //todo:记录日志


        //        //返回消息
        //        HttpResponseMessage httpResponse = new HttpResponseMessage();
        //        HttpContent httpContent = JsonContent.Create(Result.Fail("系统内部错误,请查看日志。", ResultStatus.SysError));
        //        httpResponse.Content = httpContent;
        //        actionExecutedContext.Response = httpResponse;
        //    });
        //}

        public void OnException(ExceptionContext context)
        {
            context.ExceptionHandled = true;
            context.HttpContext.Request.GetDisplayUrl();
            string param = context.HttpContext.Request.Method.ToString();
            //todo:记录日志
            AppInstance.Current.GetLogger().LogError(context.Exception, $"系统内部错误:请求地址{context.HttpContext.Request.GetDisplayUrl()}");
            //返回消息
            context.Result = new JsonResult(Result.Fail("系统内部错误,请查看日志", ResultStatus.SysError, context.Exception.GetAllMessage()));

        }
    }
}
